package com.tencent.iov.cowin.befsale.clue.service.clue.impl;

import com.github.pagehelper.Page;
import com.google.common.collect.Lists;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueOrderAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.AddClueOrderRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.response.ClueOrderResponse;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.ClueOrder;
import com.tencent.iov.cowin.befsale.clue.repository.clue.ClueOrderManager;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueOrderService;
import com.tencent.iov.cowin.befsale.clue.value.enums.ClueOrderStatusEnum;
import com.software.boot.common.exception.BusinessException;
import com.software.boot.common.exception.NEError;
import com.software.boot.common.model.dao.OrderField;
import com.software.boot.common.model.dao.PageRequest;
import com.software.boot.common.model.dao.PageResponse;
import com.software.boot.common.util.BeanUtil;
import com.software.boot.common.util.EmptyUtils;
import com.software.boot.common.util.ValidateUtils;
import com.software.common.config.SearchLocalHeader;
import com.software.common.enums.DeleteEnum;
import com.software.common.enums.SCRMRequestHeaderEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Describe: 线索订单表_Service实现层
 * @author: whp
 * @created: 2021-12-21 16:16:16
 * @version: 1.0
 */
@Service
public class ClueOrderServiceImpl implements ClueOrderService {

    @Autowired
    private ClueOrderManager clueOrderManager;

    @Override
    public ClueOrderResponse getDetailById(Long id) {
        //验证请求参数
        ValidateUtils.checkLongNotNullAndGTZero(id, "ID不能为空或小于0");
        // 处理业务
        ClueOrder clueOrder = clueOrderManager.getDetailById(id);
        if (EmptyUtils.isNotEmpty(clueOrder)) {
            return BeanUtil.copy(clueOrder, ClueOrderResponse.class);
        }
        //返回结果
        return null;
    }

    /**
     * 单条数据插入ClueOrder
     *
     * @param request
     * @return 插入的条数
     */
    @Override
    public int insert(ClueOrder request) {
        /** 1 验证请求参数 */
        /** 2 处理业务 */
        int count = clueOrderManager.insert(request);
        /** 3 封装返回值 */
        return count;
    }

    /**
     * 批量插入ClueOrder
     *
     * @param requests
     * @return 批量插入的条数
     */
    @Override
    public int insertBatch(List<ClueOrder> requests) {
        /** 1 验证请求参数 */
        /** 2 处理业务 */
        int count = clueOrderManager.insertBatch(requests);
        /** 3 封装返回值 */
        return count;
    }


    /**
     * 单条ClueOrder更新
     *
     * @param request
     * @return 更新的条数
     */
    @Override
    public int update(ClueOrder request) {

        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(request, "参数错误");
        /** 2 处理业务 */
        ClueOrderAssembler.initAddClueOrderRequest(request);
        int count = clueOrderManager.update(request);
        /** 3 返回对象 */
        return count;
    }

    /**
     * 通过ID删除数据
     *
     * @param request
     * @return 删除的条数
     */
    @Override
    public int delete(ClueOrder request) {
        Long id = request.getId();
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(id, "请求参数不能为空");
        ValidateUtils.checkLongNotNullAndGTZero(id, "ID不能为空或小于0");
        /** 2 处理业务 */
        ClueOrder clueOrder = new ClueOrder();
        clueOrder.setId(id);
//		clueOrder.setDelete(DeleteEnum.DETELED.getCode());
        int count = clueOrderManager.update(clueOrder);
        /** 3 返回对象 */
        return count;
    }

    /**
     * 根据条件查询对象对象list列表
     *
     * @param request
     * @return 查询结果
     */
    @Override
    public List<ClueOrder> getListByParam(ClueOrder request) {
        /** 1 验证请求参数 */
        //可以设置排序

        request.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));

        /** 2 处理业务 */
        List<ClueOrder> queryList = clueOrderManager.getListByParam(request);
        /** 3 返回结果 */
        if (CollectionUtils.isNotEmpty(queryList)) {
            return BeanUtil.copyByList(queryList, ClueOrder.class);
        }
        return new ArrayList<>();
    }

    /**
     * 根据条件查询对象list记录
     *
     * @param request
     * @return 分页对象
     */
    @Override
    public PageResponse<ClueOrder> getPageByParam(PageRequest<ClueOrder> request) {
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(request, "请求参数不能为空");
        //可以设置排序 query.orderByCreatedTime(true);
        /** 2 处理业务 */
        RowBounds rowBounds = new RowBounds(request.getPageNum(), request.getPageSize());

        ClueOrder query = request.getParamData();
        query.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        query.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        query.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));

        Page<ClueOrder> queryPageList = clueOrderManager.getPageByParam(request.getParamData(), rowBounds);
        PageResponse<ClueOrder> pageResponse = new PageResponse<>();
        pageResponse.converPageResponse(pageResponse, queryPageList, request);
        pageResponse.setDataList(BeanUtil.copyByList(queryPageList.getResult(), ClueOrder.class));
        /** 3 返回结果 */
        return pageResponse;
    }

    @Override
    public ClueOrderResponse getOneByParam(ClueOrder request) {
        ValidateUtils.checkObjNull(request, "请求参数不能为空");

        request.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));

        ClueOrder clueOrder = clueOrderManager.getOneByParam(request);
        if (EmptyUtils.isEmpty(clueOrder)) {
            return null;
        }
        return BeanUtil.copy(clueOrder, ClueOrderResponse.class);
    }

    @Override
    public Long insertOrUpdateClueOrder(AddClueOrderRequest request) {
        ValidateUtils.checkObjNull(request, "订单参数不存在");
        ClueOrder clueOrder = ClueOrderAssembler.transformPOToResponseVo(request, ClueOrder.class);
        if (EmptyUtils.isEmpty(clueOrder)) {
            throw new BusinessException(NEError.METHOD_ARGUMENT_INVALIDATE, "线索订单信息错误");
        }
        clueOrder.setStatus(ClueOrderStatusEnum.ORDERED.getCode());

        ClueOrder orderQueryRequest = new ClueOrder();
        orderQueryRequest.setClueId(request.getClueId());
        orderQueryRequest.setDeleted(DeleteEnum.INIT.getFlag());
        OrderField orderField = new OrderField("id", "desc");
        orderQueryRequest.setOrderFields(Lists.newArrayList(orderField));
        ClueOrder existClueOrder = clueOrderManager.getOneByParam(orderQueryRequest);

        int result;
        if (EmptyUtils.isEmpty(existClueOrder)) {
            ClueOrderAssembler.initAddClueOrderRequest(clueOrder);
            result = clueOrderManager.insert(clueOrder);
        } else {
            clueOrder.setId(existClueOrder.getId());
            ClueOrderAssembler.initUpdateClueOrderRequest(clueOrder);
            result = clueOrderManager.update(clueOrder);
        }
        if (result <= 0) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "保存或更新订单信息失败");
        }
        return clueOrder.getId();
    }

    @Override
    public Long deliveryCar(Long cluId) {
        ValidateUtils.checkLongGTZero(cluId, "交车时，线索ID不可以为null ");
        ClueOrder orderQueryRequest = new ClueOrder();
        orderQueryRequest.setClueId(cluId);
        orderQueryRequest.setDeleted(DeleteEnum.INIT.getFlag());
        OrderField orderField = new OrderField("id", "desc");
        orderQueryRequest.setOrderFields(Lists.newArrayList(orderField));
        ClueOrder existClueOrder = clueOrderManager.getOneByParam(orderQueryRequest);
        if (EmptyUtils.isEmpty(existClueOrder)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "线索跟进-交车 订单信息不存在");
        }

        ClueOrder updateClueOrder = new ClueOrder();
        updateClueOrder.setId(existClueOrder.getId());
        updateClueOrder.setStatus(ClueOrderStatusEnum.DELIVERY.getCode());
        ClueOrderAssembler.initUpdateClueOrderRequest(updateClueOrder);
        int clueOrderResult = clueOrderManager.update(updateClueOrder);
        if (clueOrderResult <= 0) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "线索跟进-交车失败");
        }
        return existClueOrder.getId();
    }
}
